package com.hmall.order.Listener;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hmall.common.client.ItemApi;
import com.hmall.common.entity.Item;
import com.hmall.order.mapper.OrderDetailMapper;
import com.hmall.order.mapper.OrderMapper;
import com.hmall.order.pojo.Order;
import com.hmall.order.pojo.OrderDetail;
import com.hmall.order.web.OrderController;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class RabbitLMQListener {

    @Autowired
    private OrderController orderController;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private ItemApi itemApi;


    @RabbitListener(
            bindings = @QueueBinding(
                    value = @Queue(name = "DarkMall.delay.queue"),
                    exchange = @Exchange(name = "DarkMall.delay.direct", delayed = "true"),
                    key = "delay"
            )

    )
    public void listenDarkMallDlQueue(String orderId) {
        log.info("--------接收到来自DarkMall.delay.queue的消息：{}------------",orderId);
        // 调用orderController查询订单
        Order order = orderController.queryOrderById(Long.valueOf(orderId));
        // 判断支付状态是否是未支付
        if (order.getStatus() == 1){

            QueryWrapper<OrderDetail> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("order_id", orderId);
            // 根据orderId查询出订单细节表
            OrderDetail orderDetail = orderDetailMapper.selectOne(queryWrapper);
            // 得到购买的数量
            Integer num = orderDetail.getNum();
            // 设置状态为支付取消
            order.setStatus(5);
            orderMapper.updateById(order);
            // 远程调用得到item具体数据
            Item item = itemApi.findItemById(orderDetail.getItemId());
            // 恢复库存数量
            item.setStock(item.getStock() + num);
            // 远程调用直接更新
            itemApi.modifyItem(item);
        }


    }


}
